/*
 *  printer.c
 *  scheme2
 *
 *  Created by Leo Katzenstein on 5/26/07.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */

#include "scheme.h"

static void print_list( Pair *l)
{
	while ( l ) {
		pexp1(l->car);
		l = l->cdr;
		if (atom(l)) {
			if ( l ) {
				printf( " . " );
				pexp1( l );
			}
			return;
		}
		printf( " " );
	}
	error( "print_list: called with null" );
}

void pexp1( Pair *e )
{
	int el;  /* environment level */
	Pair *ep;
	
	if ( e == NULL )
		printf( "nil" );
	else if ( is_fixnum( e ) )
		printf( "%d", nval(e) );
	else if ( is_double( e ) )
		printf( "%f", dval(e) );
	else if ( is_symbol( e ) )
		printf("%s", pname(e));
	else if ( is_func( e ) )
		printf( "<compiled function(0x%x)>", e->cdr );
	else if ( is_lambda(e) ) {
		for ( el=0, ep=CADR(e); ep->cdr; ep=ep->cdr )
			el += 1;
		printf( "(lambda env(%d) ", el );
		
		print_list(e->cdr->cdr);
		printf( ")\n" );
	} else
		{
			/* this is a non null list */
			printf( "(" );
			print_list( e );
			/*
			pexp1( e->car );
			for ( e = e->cdr; e; e = e->cdr )
			{
				printf( " " );
				pexp1( e->car );				
			}
			*/
			printf( ")" );
		}
}

void pexp( Pair *e )
{
	pexp1( e );
	printf( "\n" );
}
